<template>
  <div class="page-container">
    <div class="search-container" style="display: flex; align-items: center; justify-content: space-between;">
      <el-button type="success" @click="handleAdd" class="add-btn">
        <el-icon><Plus /></el-icon>添加分类
      </el-button>

      <div style="display: flex; align-items: center;">
        <el-input v-model="searchQuery" placeholder="请输入分类名称搜索" class="search-input" clearable
          @clear="getCategoryList" @keyup.enter="getCategoryList" style="width: 300px; margin-right: 10px;">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="info" @click="getCategoryList" class="search-btn" style="margin-right: 10px;">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button type="danger" @click="handleClear" class="clear-btn">
          <el-icon><Delete /></el-icon>清除
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="categoryList" class="custom-table" :header-cell-style="{
      background: '#f6f8f9',
      color: '#606266',
      fontWeight: '500',
      fontSize: '14px'
    }" :cell-style="{
      padding: '12px 0',
      fontSize: '14px',
      color: '#606266'
    }" :row-style="{
      height: '60px',
      transition: 'background-color 0.3s'
    }" border stripe highlight-current-row>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="分类名称" prop="type" min-width="120" align="center">
        <template #default="scope">
          <el-tag :style="{ backgroundColor: '#e8f4ff', color: '#409EFF', border: 'none' }">{{ scope.row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="description" min-width="200" align="center" show-overflow-tooltip />
      <el-table-column label="创建时间" prop="created_at" min-width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updated_at" min-width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.updated_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="scope">
          <div style="display: flex; justify-content: center; gap: 10px;">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)" class="edit-btn">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)" class="delete-btn">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" background class="custom-pagination" />
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog :title="dialogType === 'add' ? '添加分类' : '编辑分类'" v-model="dialogVisible" width="500px"
      :close-on-click-modal="false" destroy-on-close class="category-dialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" class="category-form">
        <el-form-item label="分类名称" prop="type">
          <el-input v-model="form.type" placeholder="请输入分类名称" class="form-input" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入分类描述" class="form-input" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleSubmit" class="submit-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const categoryList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')

// 表单相关
const formRef = ref(null)
const form = reactive({
  id: null,
  type: '',
  description: ''
})

// 表单验证规则
const rules = {
  type: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入分类描述', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取分类列表
const getCategoryList = async () => {
  loading.value = true
  try {
    const res = await request.get('/types/search', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        name: searchQuery.value || undefined
      }
    })
    if (res.code === 200 && res.data) {
      categoryList.value = res.data.list
      total.value = res.data.total
      
      if (categoryList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
        await getCategoryList()
        return
      }
    } else {
      categoryList.value = []
      total.value = 0
      ElMessage.warning('未找到相关数据')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
    categoryList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getCategoryList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getCategoryList()
}

// 添加分类
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = null
  form.type = ''
  form.description = ''
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/types/add', form).then(res => {
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
          dialogVisible.value = false
          currentPage.value = 1
          getCategoryList()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      }).catch(error => {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      })
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该分类吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    request.delete('/types/delete', {
      data: { id: row.id }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getCategoryList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    }).catch(error => {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    })
  })
}

// 添加清除功能
const handleClear = () => {
  searchQuery.value = ''
  currentPage.value = 1
  getCategoryList()
}

onMounted(() => {
  getCategoryList()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
}

.add-btn {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

.add-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.add-btn:focus,
.search-btn:focus,
.clear-btn:focus,
.edit-btn:focus,
.delete-btn:focus {
  outline: none !important;
  box-shadow: none !important;
}

.search-btn {
  background-color: #e8f4ff;
  border-color: #e8f4ff;
  color: #409EFF;
}

.search-btn:hover {
  background-color: #d9ecff;
  border-color: #d9ecff;
}

.clear-btn {
  background-color: #F56C6C;
  border-color: #F56C6C;
}

.clear-btn:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  margin: 20px 0;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #e8f4ff !important;
}

.edit-btn {
  background-color: #409EFF;
  border-color: #409EFF;
}

.edit-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.delete-btn {
  background-color: #F56C6C;
  border-color: #F56C6C;
}

.delete-btn:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409EFF;
}
</style>